import axios, { AxiosInstance } from "axios";
// 创建实例并配置默认参数
const api:AxiosInstance = axios.create({
  baseURL: "http://192.168.10.130:5000",
  // baseURL: "http://localhost:5000",
  timeout: 10000,
  headers: { "Content-Type": "application/json" }
});

// 请求拦截器：自动添加 Token
api.interceptors.request.use(config => {
  const token = localStorage.getItem("token");
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

// 响应拦截器：统一错误处理
api.interceptors.response.use(
  response => 
    Promise.resolve(response.data), // 直接返回响应数据
  error => {
    if (error.response.status === 401) {
      alert("登录过期，请重新登录");
      // router.push("/login");
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);

export default api; // 导出实例